package exercise;

import java.util.Arrays;

public class LC289 {
    public void gameOfLife(int[][] board) {
        int m = board.length, n = board[0].length;
        int[][] boardCopy = new int[m][n];
        int[] rowOffset = {-1, -1, -1, 0, 0, 1, 1, 1};
        int[] colOffset = {-1, 0, 1, -1, 1, -1, 0, 1};
        for (int i = 0; i < m; i++) {
            System.arraycopy(board[i], 0, boardCopy[i], 0, n);
        }


        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                int status = board[i][j];
                int count = 0;
                for (int k = 0; k < 8; k++) {
                    int newRow = i + rowOffset[k];
                    int newCol = j + colOffset[k];

                    if (isInBoard(newRow, newCol, board)) {
                        if (boardCopy[newRow][newCol] == 1)
                            count++;
                    }
                }
                if (count < 2) board[i][j] = 0;
                else if (count > 3 && status == 1) board[i][j] = 0;
                else if (status == 0 && count == 3) board[i][j] = 1;
            }
        }
    }

    private boolean isInBoard(int newRow, int newCol, int[][] board) {
        return newRow >= 0 && newRow < board.length && newCol >= 0 && newCol < board[0].length;
    }

    public static void main(String[] args) {
        LC289 lc289 = new LC289();
        int[][] board = {{0, 1, 0}, {0, 0, 1}, {1, 1, 1}, {0, 0, 0}};
        lc289.gameOfLife(board);
        for (int[] x : board) {
            System.out.println(Arrays.toString(x));
        }
    }
}
